package com.hp.ecs.xqa.util;

import java.math.BigDecimal;
import java.util.List;

public class HqlUtil {

	/**
	 * and field in(?,...,)
	 * 
	 * @param hql
	 * @param field
	 * @param length
	 * @return StringBuilder
	 */
	public static StringBuilder andIn(StringBuilder hql, String field, int length) {
		return in(hql, field, length, "and");
	}

	/**
	 * or field in(?,...,)
	 * 
	 * @param hql
	 * @param field
	 * @param length
	 * @return
	 * @since Fan Houjun 2009-12-8
	 */
	public static StringBuilder orIn(StringBuilder hql, String field, int length) {
		return in(hql, field, length, "or");
	}

	public static StringBuilder in(StringBuilder hql, String field, int length) {
		return in(hql, field, length, null);
	}

	/**
	 * field in(?,...,)
	 * 
	 * @param hql
	 * @param field
	 * @param length
	 * @param opt 操作符
	 * @return
	 * @since Fan Houjun 2009-12-8
	 */
	public static StringBuilder in(StringBuilder hql, String field, int length, String opt) {
		if (length > 0) {
			if (!StringUtil.isEmpty(opt)) {
				hql.append(' ').append(opt);
			}
			hql.append(' ').append(field).append(" in (");
			for (int i = 0; i < length; i++) {
				hql.append('?').append(',');
			}
			StringUtil.delLastChar(hql, ',').append(')');
		}
		return hql;
	}

	public static Number toNumber(List list) {
		return toNumber(list, 0);
	}

	public static BigDecimal toBigDecimal(List list) {
		if (list == null || list.isEmpty() || list.get(0) == null) {
			return BigDecimal.ZERO;
		}
		Number number = (Number)list.get(0);
		if (number instanceof BigDecimal) {
			return (BigDecimal)number;
		}
		return new BigDecimal(number.doubleValue());
	}

	public static Number toNumber(List list, Number dft) {
		if (list == null || list.isEmpty() || list.get(0) == null) {
			return dft;
		}
		return (Number)list.get(0);
	}

	public static String buildEnumDataHql(String type) {
		return "from cn.lf.vo." + type.replaceAll("\\.", " s where s.") + "=?";
	}
}
